#导入milvusClient和DataType模块，用于连接MIilvus服务器并操作数据类型
from attr.validators import max_len
from  pymilvus import (
connections,MilvusClient,
FieldSchema,CollectionSchema,DataType,
Collection,utility
)
import random

#连接Milvus服务器
client = MilvusClient(
    uri="http://49.234.21.142:19530"
)

# #删除已经存在的集合
# if client.has_collection("book"):
#     client.delete(collection_name="book")
#
# #定义字段
# fields = [
#     FieldSchema(name="book_id",dtype=DataType.INT64,is_primary=True,auto_id=True),
#     FieldSchema(name="title",dtype=DataType.VARCHAR,max_length=200),
#     FieldSchema(name="category",dtype=DataType.VARCHAR,max_length=50),
#     FieldSchema(name="price",dtype=DataType.DOUBLE),
#     FieldSchema(name="book_intro",dtype=DataType.FLOAT_VECTOR,dim=4)
# ]
#
# #创建集合Schema
# schema = CollectionSchema(
#     fields=fields,
#     description="Book search collection"
# )
#
# #创建集合
# client.create_collection(collection_name="book",schema=schema)
#
# #生成测试数据
# num_books = 1000
# categories = ["科幻","科技","文学","历史","前端","人文"]
# titles = ["量子世界","AI简史","时光之轮","文明起源","未来简史","数据科学"]
#
# data = []
# for i in range(num_books):
#     data.append({
#         "title": f"{random.choice(titles)}_{i}",
#         "category": random.choice(categories),
#         "price": round(random.uniform(10,100),2),
#         "book_intro": [random.random() for _ in range(4)],
#     })
# #批量插入
# insert_result = client.insert(collection_name="book",data=data)
#
# print(f"插入数据量:{len(insert_result["ids"])}")

#第二步
#准备索引参数,为"vector"字段创建索引
# index_params = MilvusClient.prepare_index_params()
# index_params.add_index(
#     field_name="book_intro",
#     metric_type="L2",
#     index_type="IVF_FLAT",
#     index_name ="vector_index",
#     params={"nlist":128}
# )
#
# #创建索引，不等待索引创建完成即返回
# client.create_index(
#     collection_name="book",
#     index_params=index_params,
# )
# print("索引创建完成")
#
# #加载数据到内存
# client.load_collection(collection_name="book")

#第三步 查询结果
query_vector = [random.random() for _ in range(4)] #生成4个随机值

print(f"查询向量:“{query_vector}")

results = client.search(
    collection_name="book",
    data=[query_vector], #向量
    output_fields=["title","category","price"],
    limit=3,
    filter="category=='科幻' and price<50", #标量
    search_params={"nprobe":10}
)
print(results)

#解析结果
print("\n科幻类且价格<50的搜索结果:")
for result in results[0]:
    print(f"ID: {result['book_id']}")
    print(f"距离: {result['distance']:.4f}")
    print(f"标题: {result['entity']['title']}")
    print(f"价格: {result['entity']['title']}")
    print("_" *30)
